using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

namespace Framework
{
    /// <summary>
    /// 解决嵌套使用ScrollRect时的Drag冲突问题,将该脚本放置到内层ScrollRect上
    /// </summary>
    public class NestedScrollRect : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    {
        private ScrollRect parentScrollRect;
        private ScrollRect scrollRect;

        void Awake()
        {
            scrollRect = GetComponent<ScrollRect>();
            var plist = GetComponentsInParent<ScrollRect>();
            if (plist.Length > 0)
            {
                parentScrollRect = plist[1];
            }
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            if (parentScrollRect != null)
            {
                parentScrollRect.OnBeginDrag(eventData);
            }
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (parentScrollRect == null)
            {
                return;
            }
            parentScrollRect.OnDrag(eventData);
            float angle = Vector2.Angle(eventData.delta, Vector2.up);
            if (angle > 45f && angle < 135f)
            {
                scrollRect.enabled = !scrollRect.vertical;
                parentScrollRect.enabled = scrollRect.vertical;
            }
            else
            {
                parentScrollRect.enabled = !scrollRect.vertical;
                scrollRect.enabled = scrollRect.vertical;
            }
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            if (parentScrollRect == null)
            {
                return;
            }
            parentScrollRect.OnEndDrag(eventData);
            parentScrollRect.enabled = true;
            scrollRect.enabled = true;
        }
    }
}